package com.qiwenshare.stock.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.qiwenshare.stock.common.HttpsUtils;
import com.qiwenshare.stock.domain.StockInfo;
import com.qiwenshare.stock.domain.StockBidBean;
import com.qiwenshare.stock.domain.StockDayInfo;
import com.qiwenshare.stock.domain.StockWeekInfo;
import com.qiwenshare.stock.dto.RangeBreakDTO;
import com.qiwenshare.stock.dto.StockDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;

/**
 * @ClassName DataUtil
 * @Description TODO
 * @Author peng.zhang
 * @Date 16:26 2023/6/5
 * @Version 1.0
 **/
@Slf4j
@Component
public class DataUtil {
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 32, 2,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(10000),
            new ThreadFactoryBuilder().setNamePrefix("data-collect-%d").build());
    @Resource
    private RedisTemplate<String, StockDayInfo> redisTemplate;
    private static RedisTemplate<String, StockDayInfo> staticRedisTemplate;

    @PostConstruct
    public void initRedis() {
        staticRedisTemplate = this.redisTemplate;
    }

    /**
     * 尾盘策略
     */
    public static List<StockInfo> tailBuy() {
        List<StockInfo> filterList = new ArrayList<>();
        List<StockInfo> list = DataUtil.getStockList();
        for (StockInfo s : list) {
            //涨跌幅 3%-5%
            if (s.getUpDownRange() > 3 && s.getUpDownRange() < 5) {
                //量比大于1
                if (s.getQuantityRelative() > 1) {
                    //换手率在5%-10%
                    if (s.getTurnOverrate() > 5 && s.getTurnOverrate() < 10) {
                        //流通市值在50亿-200亿
                        if (s.getFlowMarketValue() > 5_000_000_000D && s.getFlowMarketValue() < 20_000_000_000D) {
                            log.info("股票代码:{},股票名称:{},当前涨跌幅:{},量比:{},换手率:{},流通市值:{}",
                                    s.getStockNum(), s.getStockName(), s.getUpDownRange(),
                                    s.getQuantityRelative(), s.getTurnOverrate(), s.getFlowMarketValue());
                            filterList.add(s);
                            //在筛选成交量持续放大的，
                        }
                    }
                }
            }
        }
        return filterList;
    }

    /**
     * 动态波动区间突破策略
     * 1、昨日振幅=昨日最高价-昨日最低价；
     * 2、今日行情区间上轨=今日开盘价+N*昨日振幅；
     * 3、今日行情区间下轨=今日开盘价-N*昨日振幅；
     * 4、突破上轨，买入开仓做多；
     * 5、突破下轨，卖出开仓做空；
     * 6、在当日收盘时平仓。
     * 其中变量N的取值范围较为灵活，可以依据交易品种的波动属性和个人交易经验进行变换。
     * 通常情况下，N的取值范围位于0.5-0.8之间。
     */
    public static List<RangeBreakDTO> rangeBreak(boolean all, Date currentDay) {
        List<RangeBreakDTO> resultList = new ArrayList<>();
        List<StockInfo> filterList = new ArrayList<>();
        List<StockInfo> list = DataUtil.getStockList();
        double n = 0.6;
        for (StockInfo s : list) {
            //量比大于1
            if (s.getQuantityRelative() > 1) {
                //换手率大于1.1
                if (s.getTurnOverrate() > 1.1) {
                    //涨幅小于在6%
                    if (s.getUpDownRange() < 6) {
                        //流通市值在50亿-200亿
                        if (s.getFlowMarketValue() > 5_000_000_000D && s.getFlowMarketValue() < 20_000_000_000D) {
                            filterList.add(s);
                        }
                    }
                }
            }
        }
        CountDownLatch latch = new CountDownLatch(filterList.size());
        log.info("初筛剩余{}条", filterList.size());
        for (StockInfo s : filterList) {
            //区间计算
            //(1)N日High的最高价HH,N日Close的最低价LC;
            //(2)N日Close的最高价HC,N日Low的最低价LL;
            //(3)Range = Max(HH-LC,HC-LL)
            //(4)上轨BuyLine = Open + K1×Range
            //(5)下轨SellLine = Open - K2×Range。
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        StockDayInfo preDayInfo = staticRedisTemplate.opsForValue().get(s.getStockNum());
                        if (preDayInfo == null) {
                            preDayInfo = getPreStockDayInfo(s.getStockNum());
                            staticRedisTemplate.opsForValue().set(s.getStockNum(), preDayInfo);
                        }
                        if (preDayInfo != null && preDayInfo.getDate() != null) {
                            double range = preDayInfo.getHigh() - preDayInfo.getLow();
                            double highLine = s.getOpen() + n * range;
                            double lowLine = s.getOpen() - n * range;
                            //当前价格突破区间上线,并且今日未突破过区间下限
                            double price = s.getClose();
                            if (all) {
                                price = s.getHigh();
                            }
                            if (price > highLine && s.getLow() > lowLine) {
                                RangeBreakDTO dto = new RangeBreakDTO();
                                dto.setCurrentPrice(s.getClose());
                                dto.setStockName(s.getStockName());
                                dto.setStockNum(s.getStockNum());
                                dto.setHighLinePrice(highLine);
                                dto.setLowLinePrice(lowLine);
                                dto.setCurrentRange(s.getUpDownRange());
                                dto.setQuantityRelative(s.getQuantityRelative());
                                dto.setTurnOverrate(s.getTurnOverrate());
                                resultList.add(dto);
                            }
                        }
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return resultList;
    }


    public static List<StockInfo> getStockListByScript() {
        String url = "http://86.push2.eastmoney.com/api/qt/clist/get";
        List<StockInfo> stockBeanList = new ArrayList<StockInfo>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("pn", "1");
        param.put("pz", "8000");
        param.put("po", "1");
        param.put("np", "1");
        param.put("ut", "bd1d9ddb04089700cf9c27f6f7426281");
        param.put("fltt", "2");
        param.put("invt", "2");
        param.put("fid", "f3");
        param.put("fs", "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048");//沪深京A
        param.put("fields", "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f38,f39,f22,f11,f62,f128,f136,f115,f152,f297");
        String sendResult = HttpsUtils.doGetString(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        JSONArray diff = data.getJSONArray("diff");
        for (Object o : diff) {
            Map<String, Object> map = (Map) o;
            StockInfo stockBean = new StockInfo();
            stockBean.setStockNum((String) map.get("f12"));
            stockBean.setStockName((String) map.get("f14"));
            stockBean.setTotalFlowShares(objectToBigDecimal(map.get("f39")));
            stockBean.setTotalShares(objectToBigDecimal(map.get("f38")));
            stockBean.setUpDownRange(objectToBigDecimal(map.get("f3")));
            stockBean.setTurnOverrate(objectToBigDecimal(map.get("f8")));
            stockBean.setUpDownPrices(objectToBigDecimal(map.get("f4")));
            stockBean.setOpen(objectToBigDecimal(map.get("f17")));
            stockBean.setClose(objectToBigDecimal(map.get("f2")));
            stockBean.setHigh(objectToBigDecimal(map.get("f15")));
            stockBean.setLow(objectToBigDecimal(map.get("f16")));
            stockBean.setPreClose(objectToBigDecimal(map.get("f18")));
            stockBean.setVolume(objectToBigDecimal(map.get("f5")));
            stockBean.setAmount(objectToBigDecimal(map.get("f6")));
            stockBean.setAmplitude(objectToBigDecimal(map.get("f7")));
            stockBean.setTotalMarketValue(objectToBigDecimal(map.get("f20")));
            stockBean.setFlowMarketValue(objectToBigDecimal(map.get("f21")));
            stockBean.setListingDate(String.valueOf(map.get("f26")));
            //剔除ST,*ST,N
            if (stockBean.getStockName().startsWith("ST")
                    || stockBean.getStockName().startsWith("*ST")
                    || stockBean.getStockName().startsWith("N")) {
                continue;
            }
            //不满足0%-5%
            if (stockBean.getUpDownRange() > 5 || stockBean.getUpDownRange() < 0) {
                continue;
            }
            stockBeanList.add(stockBean);
        }
        return stockBeanList;
    }

    /**
     * 获取股票列表
     *
     * @return
     */
    public static List<StockInfo> getStockList() {
        String url = "http://49.push2.eastmoney.com/api/qt/clist/get";
        List<StockInfo> stockBeanList = new ArrayList<StockInfo>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("pn", 1);
        param.put("pz", 10000);
        param.put("po", "1");
        param.put("np", "1");
        param.put("ut", "bd1d9ddb04089700cf9c27f6f7426281");
        param.put("fltt", "2");
        param.put("invt", "2");
        param.put("fid", "f3");
        //北交所股票代码8开头
        //上证主板股票代码是60开头、科创板股票代码是688开头；
        //深证主板股票代码是000开头、中小板股票代码002开头、创业板300开头、B股代码200开头；
        param.put("fs", "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048");
        param.put("wbp2u", "|0|0|0|web");
        param.put("fields", "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152");
        String sendResult = HttpUtil.get(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        JSONArray diff = data.getJSONArray("diff");
        for (Object o : diff) {
            Map<String, Object> map = (Map) o;
            StockInfo stockBean = new StockInfo();
            stockBean.setStockNum((String) map.get("f12"));
            stockBean.setStockName((String) map.get("f14"));
            stockBean.setTotalFlowShares(objectToBigDecimal(map.get("f39")));
            stockBean.setTotalShares(objectToBigDecimal(map.get("f38")));
            stockBean.setUpDownRange(objectToBigDecimal(map.get("f3")));
            stockBean.setTurnOverrate(objectToBigDecimal(map.get("f8")));
            stockBean.setUpDownPrices(objectToBigDecimal(map.get("f4")));
            stockBean.setOpen(objectToBigDecimal(map.get("f17")));
            stockBean.setClose(objectToBigDecimal(map.get("f2")));
            stockBean.setHigh(objectToBigDecimal(map.get("f15")));
            stockBean.setLow(objectToBigDecimal(map.get("f16")));
            stockBean.setPreClose(objectToBigDecimal(map.get("f18")));
            stockBean.setVolume(objectToBigDecimal(map.get("f5")));
            stockBean.setAmount(objectToBigDecimal(map.get("f6")));
            stockBean.setAmplitude(objectToBigDecimal(map.get("f7")));
            stockBean.setTotalMarketValue(objectToBigDecimal(map.get("f20")));
            stockBean.setFlowMarketValue(objectToBigDecimal(map.get("f21")));
            stockBean.setListingDate(String.valueOf(map.get("f26")));
            stockBean.setQuantityRelative(objectToBigDecimal(map.get("f10")));
            //剔除ST,*ST,N
            if (stockBean.getStockName().startsWith("ST")
                    || stockBean.getStockName().startsWith("*ST")
                    || stockBean.getStockName().startsWith("N")) {
                continue;
            }
            //剔除科创板、北交所
            if (stockBean.getStockNum().startsWith("68")
                    || stockBean.getStockNum().startsWith("8")) {
                continue;
            }
            //剔除退市的
            if (stockBean.getFlowMarketValue() == 0) {
                continue;
            }
            stockBeanList.add(stockBean);
        }
        return stockBeanList;
    }

    /**
     * 根据代码获取日线数据
     */
    public static List<StockDayInfo> getStockDayInfoByNum(String stockNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -400);
        String url = "http://push2his.eastmoney.com/api/qt/stock/kline/get";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("fields1", "f1,f2,f3,f4,f5,f6");
        param.put("fields2", "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61");
        param.put("ut", "7eea3edcaed734bea9cbfc24409ed989");
        param.put("klt", "101");
        param.put("fqt", "1");
        param.put("secid", stockNum2Sid(stockNum));
        param.put("beg", DateUtil.format(calendar.getTime(), "YYYYMMdd"));
//        param.put("beg", "0");
        param.put("end", "20500000");
        String sendResult = HttpsUtils.doGetString(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        List<StockDayInfo> stockDayInfoList = new ArrayList<StockDayInfo>();
        if (data == null) {
            return stockDayInfoList;
        }
        JSONArray klines = data.getJSONArray("klines");
        for (int i = 0; i < klines.size(); i++) {
            String kline = (String) klines.get(i);
            String[] item = kline.split(",");
            StockDayInfo stockDayInfo = new StockDayInfo();
            stockDayInfo.setStockNum(data.get("code").toString());
            stockDayInfo.setStockName(data.get("name").toString());
            stockDayInfo.setDate(item[0]);
            stockDayInfo.setOpen(objectToBigDecimal(item[1]));
            stockDayInfo.setClose(objectToBigDecimal(item[2]));
            stockDayInfo.setHigh(objectToBigDecimal(item[3]));
            stockDayInfo.setLow(objectToBigDecimal(item[4]));
            stockDayInfo.setVolume(objectToBigDecimal(item[5]));
            stockDayInfo.setAmount(objectToBigDecimal(item[6]));
            stockDayInfo.setChangeRatio(objectToBigDecimal(item[8]));
            if (objectToBigDecimal(item[9]) == null) {
                stockDayInfo.setPreClose(0);
            } else {
                if (objectToBigDecimal(item[2]) == null) {
                    log.info("---------------null-------------" + stockNum);
                }
                stockDayInfo.setPreClose(objectToBigDecimal(item[2]) == null ? 0 : objectToBigDecimal(item[2]) - (objectToBigDecimal(item[9])));
            }
            stockDayInfoList.add(stockDayInfo);
        }
        return stockDayInfoList;
    }

    /**
     * 根据代码获取日线数据
     */
    public static List<StockWeekInfo> getStockWeekInfoByNum(String stockNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -600);
        String url = "http://push2his.eastmoney.com/api/qt/stock/kline/get";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("fields1", "f1,f2,f3,f4,f5,f6");
        param.put("fields2", "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61");
        param.put("ut", "7eea3edcaed734bea9cbfc24409ed989");
        param.put("klt", "102");
        param.put("fqt", "1");
        param.put("secid", stockNum2Sid(stockNum));
        param.put("beg", DateUtil.format(calendar.getTime(), "YYYYMMdd"));
        param.put("end", "20500000");
        String sendResult = HttpsUtils.doGetString(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        List<StockWeekInfo> stockWeekInfoList = new ArrayList<>();
        if (data == null) {
            return stockWeekInfoList;
        }
        JSONArray klines = data.getJSONArray("klines");
        for (int i = 0; i < klines.size(); i++) {
            String kline = (String) klines.get(i);
            String[] item = kline.split(",");
            StockWeekInfo info = new StockWeekInfo();
            info.setStockNum(data.get("code").toString());
            info.setStockName(data.get("name").toString());
            info.setDate(item[0]);
            info.setOpen(objectToBigDecimal(item[1]));
            info.setClose(objectToBigDecimal(item[2]));
            info.setHigh(objectToBigDecimal(item[3]));
            info.setLow(objectToBigDecimal(item[4]));
            info.setVolume(objectToBigDecimal(item[5]));
            info.setAmount(objectToBigDecimal(item[6]));
            info.setChangeRatio(objectToBigDecimal(item[8]));
            if (objectToBigDecimal(item[9]) == null) {
                info.setPreClose(0);
            } else {
                if (objectToBigDecimal(item[2]) == null) {
                    log.info("---------------null-------------" + stockNum);
                }
                info.setPreClose(objectToBigDecimal(item[2]) == null ? 0 : objectToBigDecimal(item[2]) - (objectToBigDecimal(item[9])));
            }
            stockWeekInfoList.add(info);
        }
        return stockWeekInfoList;
    }

    /**
     * 获取实时数据-买1-买5，卖1-卖5以及委托数量
     *
     * @param stockNum
     * @return
     */
    public static StockBidBean getRealTimeData(String stockNum) {
        String url = "http://push2.eastmoney.com/api/qt/stock/get";
        //String param = "select=ask,bid";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ut", "fa5fd1943c7b386f172d6893dbfba10b");
        param.put("invt", "2");
        param.put("fltt", "2");
        param.put("fields", "f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292");
        param.put("secid", stockNum2Sid(stockNum));
        String sendResult = HttpUtil.get(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        StockBidBean stockBidBean = new StockBidBean();
        stockBidBean.setStockNum(stockNum);
//        stockBidBean.setStockId(stockBean.getStockId());
        stockBidBean.setSellPrice5(objectToBigDecimal(data.get("f31")));
        stockBidBean.setSellCount5(objectToInteger(data.get("f32").toString()));
        stockBidBean.setSellPrice4(objectToBigDecimal(data.get("f33")));
        stockBidBean.setSellCount4(objectToInteger(data.get("f34").toString()));
        stockBidBean.setSellPrice3(objectToBigDecimal(data.get("f35")));
        stockBidBean.setSellCount3(objectToInteger(data.get("f36").toString()));
        stockBidBean.setSellPrice2(objectToBigDecimal(data.get("f37")));
        stockBidBean.setSellCount2(objectToInteger(data.get("f38").toString()));
        stockBidBean.setSellPrice1(objectToBigDecimal(data.get("f39")));
        stockBidBean.setSellCount1(objectToInteger(data.get("f40").toString()));
        stockBidBean.setBoughtPrice1(objectToBigDecimal(data.get("f19")));
        stockBidBean.setBoughtCount1(objectToInteger(data.get("f20").toString()));
        stockBidBean.setBoughtPrice2(objectToBigDecimal(data.get("f17")));
        stockBidBean.setBoughtCount2(objectToInteger(data.get("f18").toString()));
        stockBidBean.setBoughtPrice3(objectToBigDecimal(data.get("f15")));
        stockBidBean.setBoughtCount3(objectToInteger(data.get("f16").toString()));
        stockBidBean.setBoughtPrice4(objectToBigDecimal(data.get("f13")));
        stockBidBean.setBoughtCount4(objectToInteger(data.get("f14").toString()));
        stockBidBean.setBoughtPrice5(objectToBigDecimal(data.get("f11")));
        stockBidBean.setBoughtCount5(objectToInteger(data.get("f12").toString()));
        return stockBidBean;
    }

    /**
     * 获取实时数据
     *
     * @param stockNum
     * @return
     */
    public static StockDTO getCurrentStockInfo(String stockNum) {
        String url = "http://push2.eastmoney.com/api/qt/ulist/get";
        //String param = "select=ask,bid";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ut", "fa5fd1943c7b386f172d6893dbfba10b");
        param.put("np", "1");
        param.put("pn", "1");
        param.put("pz", "20");
        param.put("invt", "2");
        param.put("fltt", "2");
        param.put("fields", "f2,f3,f8,f10,f14,f15,f16,f17");
        param.put("secids", stockNum2Sid(stockNum));
        String sendResult = HttpUtil.get(url, param);
        JSONObject data = new JSONObject();
        JSONArray diff = data.getJSONArray("diff");
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
            if (data != null) {
                diff = data.getJSONArray("diff");
            }
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        Map<String, Object> map = (Map<String, Object>) diff.get(0);
        StockDTO stockDTO = new StockDTO();
        stockDTO.setStockNum(stockNum);
        stockDTO.setStockName(map.get("f14").toString());
        stockDTO.setCurrentPrice(objectToBigDecimal(map.get("f2")));
        stockDTO.setCurrentRange(objectToBigDecimal(map.get("f3")));
        stockDTO.setTurnOverrate(objectToBigDecimal(map.get("f8")));
        stockDTO.setQuantityRelative(objectToBigDecimal(map.get("f10")));
        stockDTO.setOpenPrice(objectToBigDecimal(map.get("f17")));
        stockDTO.setHigthPrice(objectToBigDecimal(map.get("f15")));
        stockDTO.setLowPrice(objectToBigDecimal(map.get("f16")));
        return stockDTO;
    }

    public static StockDayInfo getPreStockDayInfo(String stockNum) {
        StockDayInfo stockDayInfo = new StockDayInfo();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -10);
        String url = "http://push2his.eastmoney.com/api/qt/stock/kline/get";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("fields1", "f1,f2,f3,f4,f5,f6");
        param.put("fields2", "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61");
        param.put("ut", "7eea3edcaed734bea9cbfc24409ed989");
        param.put("klt", "101");
        param.put("fqt", "1");
        param.put("secid", stockNum2Sid(stockNum));
        param.put("beg", DateUtil.format(calendar.getTime(), "YYYYMMdd"));
        param.put("end", DateUtil.format(DateUtil.yesterday(), "YYYYMMdd"));
        String sendResult = HttpUtil.get(url, param);
        JSONObject data = new JSONObject();
        try {
            data = JSONObject.parseObject(sendResult).getJSONObject("data");
        } catch (JSONException e) {
            log.error("解析jsonb报错：" + data.toJSONString());
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        List<StockDayInfo> stockDayInfoList = new ArrayList<StockDayInfo>();
        if (data != null) {
            JSONArray klines = data.getJSONArray("klines");
            if (klines.size() > 0) {
                String kline = (String) klines.get(klines.size() - 1);
                String[] item = kline.split(",");
                stockDayInfo.setDate(item[0]);
                stockDayInfo.setOpen(objectToBigDecimal(item[1]));
                stockDayInfo.setClose(objectToBigDecimal(item[2]));
                stockDayInfo.setHigh(objectToBigDecimal(item[3]));
                stockDayInfo.setLow(objectToBigDecimal(item[4]));
                stockDayInfo.setVolume(objectToBigDecimal(item[5]));
                stockDayInfo.setAmount(objectToBigDecimal(item[6]));
                if (objectToBigDecimal(item[9]) == null) {
                    stockDayInfo.setPreClose(0);
                } else {
                    if (objectToBigDecimal(item[2]) == null) {
                        log.info("---------------null-------------" + stockNum);
                    }
                    stockDayInfo.setPreClose(objectToBigDecimal(item[2]) == null ? 0 : objectToBigDecimal(item[2]) - (objectToBigDecimal(item[9])));
                }
                stockDayInfoList.add(stockDayInfo);
            }
        }
        return stockDayInfo;
    }


    public static Double objectToBigDecimal(Object o) {
        try {
            return Double.valueOf(String.valueOf(o));
        } catch (NumberFormatException e) {
            return Double.valueOf(0);
        }
    }

    public static Integer objectToInteger(Object o) {
        if (o == null) {
            return null;
        }
        String str = o.toString();
        if (str.equals("-")) {
            return null;
        }
        try {
            return Integer.parseInt(o.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static String stockNum2Sid(String stockNum) {
        if (stockNum.startsWith("6")) {
            stockNum = "1." + stockNum;
        } else {
            stockNum = "0." + stockNum;
        }
        return stockNum;
    }

    public static void main(String[] args) {
        System.out.println(getStockDayInfoByNum("159889"));
    }
}
